<template>
  <div class="time-selector">
    <!-- 时间选择按钮 -->
    <el-button 
      :style="{ width: width }"
      @click="openTimeDialog"
      :loading="loading"
    >
      {{ selectedTime ? formatSelectedTime(selectedTime) : placeholder }}
    </el-button>
    <!-- 时间选择弹窗 -->
    <el-dialog
      v-model="dialogVisible"
      title="选择时间"
      width="510px"
      :append-to-body="true"
      :modal="true"
      :center="true"
      :close-on-click-modal="false"
      :close-on-press-escape="true"
      :destroy-on-close="false"
      class="time-selector-dialog"
    >
            <!-- 时间范围筛选 -->
            <div class="time-filter-section" style="margin-bottom: 10px;">
              <div class="filter-row">
                <el-date-picker
                  v-model="timeRangeFilter"
                  type="datetimerange"
                  range-separator="至"
                  start-placeholder="开始时间"
                  end-placeholder="结束时间"
                  format="YYYY-MM-DD HH:mm:ss"
                  value-format="YYYY-MM-DD HH:mm:ss"
                  style="width: 72%; margin-right: 12px;"
                  @change="handleTimeRangeFilterChange"
                  clearable
                />
                <el-button size="small" type="primary" @click="applyTimeFilter">筛选</el-button>
                <el-button size="small" @click="clearTimeFilter">清除</el-button>
              </div>
            </div>
      
      <!-- 数据列表 -->
      <el-table
        :data="paginatedTimeOptions"
        style="width: 100%"
        size="small"
        :header-cell-style="{ background: 'rgba(24, 150, 146, 0.4)', color: '#000000' }"
        :cell-style="{ background: 'transparent', color: '#000000' }"
        :row-style="{ background: 'transparent' }"
        :highlight-current-row="true"
        height="400"
        @row-click="handleRowClick"
        v-loading="loading"
      >
        <el-table-column type="index" label="序号" width="60" align="center" />
        <el-table-column prop="formattedDateTime" label="时间" align="center" />
        <el-table-column prop="dateTimeString" label="原始时间" align="center" />
      </el-table>
      
      <!-- 分页组件 -->
      <div v-if="showPagination && totalPages > 1" class="pagination-container">
        <el-pagination
          v-model:current-page="queryParams.pageNum"
          v-model:page-size="queryParams.pageSize"
          :total="totalCount"
          layout="total, pager"
          @current-change="handleCurrentChange"
          small
        />
      </div>
      
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmSelection">确定</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, watch, onMounted, toRefs, nextTick } from 'vue'
import { tableQuery } from '@/api/system/user'
import dayjs from 'dayjs'

// Props
const props = defineProps({
  // 选中的时间值
  modelValue: {
    type: String,
    default: ''
  },
  // 占位符
  placeholder: {
    type: String,
    default: '请选择时间'
  },
  // 宽度
  width: {
    type: String,
    default: '260px'
  },
  // 是否显示分页
  showPagination: {
    type: Boolean,
    default: true
  },
  // 每页显示数量
  defaultPageSize: {
    type: Number,
    default: 20
  },
  // 城市参数
  city: {
    type: String,
    default: ''
  }
})

// Emits
const emit = defineEmits(['update:modelValue', 'change', 'load-complete'])

// 查询参数 - 组件内部定义
const queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  type: 'PPI',
  city: '',
  beginTime: null,
  endTime: null
})

// 响应式数据
const timeOptions = ref([])
const filteredTimeOptions = ref([])
const timeRangeFilter = ref([])
const selectedTime = ref('')
const pageSize = ref(props.defaultPageSize)
const loading = ref(false)
const dialogVisible = ref(false)
const selectedRow = ref(null)
const totalCount = ref(0) // 总数据量，用于接口分页

// 计算属性
const totalPages = computed(() => {
  // 如果使用接口分页，使用总数计算
  if (queryParams.pageSize && queryParams.pageSize > 0) {
    return Math.ceil(totalCount.value / pageSize.value)
  }
  
  // 前端分页
  return Math.ceil(filteredTimeOptions.value.length / pageSize.value)
})

const state = reactive({
	paginatedTimeOptions:[]
})
const {paginatedTimeOptions }=toRefs(state)

// 监听 modelValue 变化
watch(() => props.modelValue, (newVal) => {
  selectedTime.value = newVal
}, { immediate: true })

// 监听选中时间变化
watch(selectedTime, (newVal) => {
  emit('update:modelValue', newVal)
  emit('change', newVal)
})

// 监听 city 参数变化，使用 nextTick 确保参数稳定后再加载数据
watch(() => props.city, async (newCity, oldCity) => {
  // 如果 city 发生变化
  if (newCity !== oldCity) {
    // 更新 queryParams.city
    queryParams.city = newCity || ''
    
    // 清空当前选择的时间
    selectedTime.value = ''
    emit('update:modelValue', '')
    
    // 重置分页
    queryParams.pageNum = 1
    
    // 使用 nextTick 确保响应式更新完成后再加载数据
    await nextTick()
    
    // 如果弹窗已打开，重新加载数据
    if (dialogVisible.value) {
      loadTimeOptions()
    }
  }
}, { immediate: false })

// 格式化选中的时间用于按钮显示
const formatSelectedTime = (dateTimeString) => {
  if (!dateTimeString) {
    return ''
  }
  
  try {
    return dayjs(dateTimeString).format('YYYY-MM-DD HH:mm:ss')
  } catch (error) {
    console.error('时间格式化错误:', error)
    return dateTimeString
  }
}

// 处理时间范围筛选变化
const handleTimeRangeFilterChange = (value) => {
  if (value && value.length === 2) {
    queryParams.beginTime = value[0]
    queryParams.endTime = value[1]
    applyTimeFilter()
  } else {
    queryParams.beginTime = null
    queryParams.endTime = null
    clearTimeFilter()
  }
}

// 应用时间筛选
const applyTimeFilter = async () => {
  if (timeRangeFilter.value && timeRangeFilter.value.length === 2) {
    queryParams.beginTime = timeRangeFilter.value[0]
    queryParams.endTime = timeRangeFilter.value[1]
    
    const startTime = new Date(timeRangeFilter.value[0])
    const endTime = new Date(timeRangeFilter.value[1])
    
  } else {
    queryParams.beginTime = null
    queryParams.endTime = null
  }
  
  // 确保使用最新的 city 值
  queryParams.city = props.city || ''
  
  // 重置到第一页
  queryParams.pageNum = 1
  
  // 使用 nextTick 确保响应式更新完成后再加载数据
  await nextTick()
  loadTimeOptions()
}

// 清除时间筛选
const clearTimeFilter = async () => {
  timeRangeFilter.value = []
  queryParams.beginTime = null
  queryParams.endTime = null
  
  // 确保使用最新的 city 值
  queryParams.city = props.city || ''
  
  queryParams.pageNum = 1
  
  // 使用 nextTick 确保响应式更新完成后再加载数据
  await nextTick()
  loadTimeOptions()
}

// 打开时间选择弹窗
const openTimeDialog = async () => {
  dialogVisible.value = true
  
  // 清空筛选条件
  timeRangeFilter.value = []
  queryParams.beginTime = null
  queryParams.endTime = null
  
  // 清空选中的行
  selectedRow.value = null
  
  // 重置分页到第一页
  queryParams.pageNum = 1
  
  // 确保使用最新的 city 值
  queryParams.city = props.city || ''
  
  // 使用 nextTick 确保响应式更新完成后再加载数据
  await nextTick()
  
  // 重新加载数据
  loadTimeOptions()
}

// 处理行点击
const handleRowClick = (row) => {
  selectedRow.value = row
  selectedTime.value = row.dateTimeString
  emit('update:modelValue', row.dateTimeString)
  emit('change', row.dateTimeString)
  dialogVisible.value = false
  console.log('选择的时间行:', row)
}

// 确认选择
const confirmSelection = () => {
  dialogVisible.value = false
  if (selectedRow.value) {
    // 日期已经在点击行时传递了，这里只需要关闭对话框
    dialogVisible.value = false
  } else {
    // 如果没有选择行，提示用户
    console.warn('请先选择一行数据')
  }
}

// 处理当前页变化
const handleCurrentChange = async (newPage) => {
    queryParams.pageNum = newPage
    // 确保使用最新的 city 值
    queryParams.city = props.city || ''
    // 使用 nextTick 确保响应式更新完成后再加载数据
    await nextTick()
    loadTimeOptions()
}

// 加载时间选项数据
const loadTimeOptions = async () => {
  try {
    loading.value = true
    // 构建查询参数，包含 city
    const params = {
      ...queryParams,
      city: props.city || ''
    }
    console.log(params,"44444");
    const response = await tableQuery(params)
    
	  if (response.code === 200) {
      const data = response.data.result || []
      const total = response.data.totalNum || response.data.total || data.length
      
      // 为每个时间项添加格式化后的时间字段
      const formattedData = data.map(item => ({
        ...item,
        formattedDateTime: dayjs(item.dateTimeString).format('YYYY-MM-DD HH:mm:ss')
      }))
      
      state.paginatedTimeOptions = formattedData
      filteredTimeOptions.value = [...formattedData]
      totalCount.value = total
      
      // 如果有数据且当前没有选择时间，自动选择第一个
      if (data.length > 0 && !selectedTime.value) {
        selectedTime.value = data[0].dateTimeString
      }
      
      emit('load-complete', formattedData)
    }
  } catch (error) {
    console.error('加载时间选项失败:', error)
    timeOptions.value = []
    filteredTimeOptions.value = []
    totalCount.value = 0
  } finally {
    loading.value = false
  }
}

// 刷新数据
const refresh = async () => {
  // 确保使用最新的 city 值
  queryParams.city = props.city || ''
  // 使用 nextTick 确保响应式更新完成后再加载数据
  await nextTick()
  loadTimeOptions()
}

// 暴露方法给父组件
defineExpose({
  refresh,
  loadTimeOptions,
  clearTimeFilter,
  applyTimeFilter
})

// 组件挂载时初始化 city 参数
onMounted(async () => {
  queryParams.city = props.city || ''
  // 使用 nextTick 确保初始化完成后再加载数据
  await nextTick()
  loadTimeOptions()
})
</script>

<style scoped lang="scss">
.time-selector {
  .el-button {
    background: rgba(24, 150, 146, 0.3);
    border: 1px solid rgba(255, 255, 255, 0.4);
    color: #ffffff;
    text-align: left;
    justify-content: flex-start;
    
    &:hover {
      background: rgba(24, 150, 146, 0.5);
      border-color: rgba(255, 255, 255, 0.6);
    }
  }
  
  .pagination-container {
    margin-top: 12px;
    display: flex;
    justify-content: center;
    
    :deep(.el-pagination) {
      .el-pagination__total,
      .el-pagination__jump,
      .el-pagination__sizes .el-select .el-input__inner {
        color: #ffffff;
      }
      
      .el-pager li {
        background: rgba(24, 150, 146, 0.2);
        border: 1px solid rgba(24, 150, 146, 0.4);
        color: #ffffff;
        
        &:hover {
          background: rgba(24, 150, 146, 0.4);
        }
        
        &.is-active {
          background: rgba(24, 150, 146, 0.8);
          border-color: rgba(24, 150, 146, 0.8);
        }
      }
      
      .btn-prev,
      .btn-next {
        background: rgba(24, 150, 146, 0.2);
        border: 1px solid rgba(24, 150, 146, 0.4);
        color: #ffffff;
        
        &:hover {
          background: rgba(24, 150, 146, 0.4);
        }
      }
    }
  }
}

// 时间选择弹窗样式
:deep(.time-selector-dialog) {
  .el-dialog {
    background: linear-gradient(135deg, rgba(24, 150, 146, 0.15) 0%, rgba(24, 150, 146, 0.1) 100%);
    border: 1px solid rgba(24, 150, 146, 0.3);
    border-radius: 12px;
    box-shadow: 
      0 6px 15px rgba(24, 150, 146, 0.2),
      0 2px 4px rgba(24, 150, 146, 0.1),
      inset 0 1px 0 rgba(255, 255, 255, 0.2);
    backdrop-filter: blur(8px);
  }
  
  .el-dialog__header {
    background: linear-gradient(135deg, rgba(24, 150, 146, 0.8) 0%, rgba(24, 150, 146, 0.6) 100%);
    border-radius: 12px 12px 0 0;
    padding: 16px 20px;
    border-bottom: 1px solid rgba(24, 150, 146, 0.4);
    
    .el-dialog__title {
      color: #ffffff;
      font-weight: 600;
      font-size: 16px;
    }
    
    .el-dialog__headerbtn {
      .el-dialog__close {
        color: #ffffff;
        font-size: 18px;
        
        &:hover {
          color: rgba(255, 255, 255, 0.8);
        }
      }
    }
  }
  
  .el-dialog__body {
    background: transparent;
    padding: 20px;
    
    .time-filter-section {
      margin-bottom: 40px;
      
      .filter-row {
        display: flex;
        align-items: center;
        gap: 8px;
        
        .el-button {
          padding: 4px 12px;
          font-size: 12px;
          background: rgba(24, 150, 146, 0.3);
          border: 1px solid rgba(255, 255, 255, 0.4);
          color: #ffffff;
          
          &:hover {
            background: rgba(24, 150, 146, 0.5);
            border-color: rgba(255, 255, 255, 0.6);
          }
        }
      }
    }
    
    // 表格样式
    :deep(.el-table) {
      .el-table__header {
        th {
          color: #000000 !important;
        }
      }
      
      .el-table__body {
        td {
          color: #000000 !important;
        }
      }
      
      .el-table__row {
        cursor: pointer;
        transition: all 0.3s ease;
        
        &:hover {
          background: rgba(24, 150, 146, 0.1) !important;
          td {
            color: #000000 !important;
            background: transparent !important;
          }
        }
        
        &.current-row {
          background: rgba(24, 150, 146, 0.2) !important;
          td {
            color: #000000 !important;
            background: transparent !important;
          }
        }
      }
    }
  }
  
  .el-dialog__footer {
    background: transparent;
    padding: 16px 20px 20px;
    border-top: 1px solid rgba(24, 150, 146, 0.2);
    
    .dialog-footer {
      display: flex;
      justify-content: flex-end;
      gap: 12px;
      
      .el-button {
        padding: 8px 16px;
        border-radius: 6px;
        font-weight: 500;
        
        &:not(.el-button--primary) {
          background: rgba(255, 255, 255, 0.1);
          border: 1px solid rgba(255, 255, 255, 0.3);
          color: #ffffff;
          
          &:hover {
            background: rgba(255, 255, 255, 0.2);
            border-color: rgba(255, 255, 255, 0.5);
          }
        }
        
        &.el-button--primary {
          background: linear-gradient(135deg, rgba(24, 150, 146, 0.8), rgba(24, 150, 146, 0.6));
          border: 1px solid rgba(24, 150, 146, 0.6);
          color: #ffffff;
          
          &:hover {
            background: linear-gradient(135deg, rgba(24, 150, 146, 1), rgba(24, 150, 146, 0.8));
            border-color: rgba(24, 150, 146, 0.8);
          }
        }
      }
    }
  }
}

// 日期选择器样式
:deep(.el-date-editor) {
  .el-input__wrapper {
    background: rgba(24, 150, 146, 0.1);
    border: 1px solid rgba(24, 150, 146, 0.4);
    border-radius: 6px;
    
    &:hover {
      border-color: rgba(24, 150, 146, 0.6);
    }
    
    &.is-focus {
      border-color: rgba(24, 150, 146, 0.8);
      box-shadow: 0 0 0 2px rgba(24, 150, 146, 0.2);
    }
    
    .el-input__inner {
      color: #ffffff;
      
      &::placeholder {
        color: rgba(255, 255, 255, 0.6);
      }
    }
    
    .el-input__suffix {
      .el-input__suffix-inner {
        color: #ffffff;
      }
    }
  }
}
</style>
